package com.igrowing.springbootinit.controller;

import cn.hutool.json.JSONUtil;
import com.igrowing.springbootinit.common.ErrorCode;
import com.igrowing.springbootinit.config.ThreadPoolExecutorConfig;
import com.igrowing.springbootinit.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Description:    // 类说明
 *
 * @ClassName: QueueController    // 类名，会自动填充
 * @Author: 周天赐        // 创建者
 * @Email: m18879004515@163.com
 * @Date: 2024/4/2 14:35   // 时间
 * @Version: 1.0     // 版本
 */
@RestController
@RequestMapping("queue")
@Slf4j
public class QueueController {

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @GetMapping("add")
    public void addTask(String name)
    {
        try {
            CompletableFuture.runAsync(()->{
                log.info("任务正在执行："+name+"执行人："+Thread.currentThread().getName());
                try {
                    Thread.sleep(600000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            },threadPoolExecutor);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.TOO_MANY_REQUEST,"当前系统繁忙请稍后再试");
        }
    }
    
    @GetMapping("get")
    public String getTask()
    {
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("队列长度", threadPoolExecutor.getQueue().size());
        hashMap.put("任务总数", threadPoolExecutor.getTaskCount());
        hashMap.put("已完成任务数", threadPoolExecutor.getCompletedTaskCount());
        hashMap.put("正在工作的线程数", threadPoolExecutor.getActiveCount());
        System.out.println(hashMap.toString());
        return JSONUtil.toJsonStr(hashMap);
    }

}

    
    
